package com.cskaoyan.service.admin.impl;

import com.cskaoyan.bean.BaseParamBo;
import com.cskaoyan.bean.BaseRespData;
import com.cskaoyan.bean.pojo.*;
import com.cskaoyan.bean.admin.promotion.Prohibition;
import com.cskaoyan.bean.admin.promotion.bo.*;
import com.cskaoyan.bean.admin.promotion.vo.*;
import com.cskaoyan.mapper.*;
import com.cskaoyan.service.admin.PromotionService;
import com.cskaoyan.util.ad.TransferUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.lang.System;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @Name : TopicVo.java
 * @Time : 2021/8/12 19:50
 * @Author : creamycandy
 * @Software : IntelliJ IDEA
 */

@Transactional
@Service
public class PromotionServiceImpl implements PromotionService {

    @Autowired
    AdMapper adMapper;

    @Autowired
    CouponMapper couponMapper;

    @Autowired
    CouponUserMapper couponUserMapper;

    @Autowired
    Prohibition prohibition;

    @Autowired
    TopicMapper topicMapper;

    @Autowired
    GrouponRulesMapper grouponRulesMapper;

    @Autowired
    GoodsMapper goodsMapper;

    @Autowired
    GrouponMapper grouponMapper;

    @Override
    public AdListVo getAdList(String name, String content, BaseParamBo param) {
        AdListVo adListVo = new AdListVo();
        PageHelper.startPage(param.getPage(), param.getLimit());
        AdExample adExample = new AdExample();
        adExample.setOrderByClause(param.getSort() + " " + param.getOrder());
        AdExample.Criteria criteria = adExample.createCriteria();
        if (name != null && !"".equals(name)) {
            criteria.andNameLike("%" + name + "%");
        }
        if (content != null && !"".equals(content)) {
            criteria.andContentLike("%" + content + "%");
        }
        criteria.andDeletedEqualTo(false);

        ArrayList<ItemsBean> items = new ArrayList<>();
        List<Ad> ads = adMapper.selectByExample(adExample);
        for (Ad ad : ads) {
            ItemsBean itemsBean = TransferUtils.Ad2Bo(ad);
            items.add(itemsBean);
        }
        PageInfo<Ad> pageInfo = new PageInfo<>();
        int total = pageInfo.getPages();
        adListVo.setTotal(total);
        adListVo.setItems(items);
        return adListVo;
    }

    @Override
    public ItemsBean updateAd(AdBo adBo) {
        Ad ad = adMapper.selectByPrimaryKey(adBo.getId());
        //未做修改判断
        if (ad.getName().equals(adBo.getName()) &&
                ad.getContent().equals(adBo.getContent()) &&
                ad.getLink().equals(adBo.getLink()) &&
                ad.getPosition().equals(adBo.getPosition()) &&
                ad.getEnabled().equals(adBo.getEnabled()) &&
                ad.getUrl().equals(adBo.getUrl())) {
            return null;
        }
        //判断内容中有禁止的内容
        ItemsBean itemsBean = isIllegal(adBo);
        if (itemsBean != null) return itemsBean;
        Ad insertAd = TransferUtils.Vo2Ad(adBo);
        long l = System.currentTimeMillis();
        Date date = new Date(l);
        insertAd.setUpdateTime(date);
        adMapper.updateByPrimaryKey(insertAd);
        ItemsBean itemsBean1 = TransferUtils.Ad2Bo(ad);
        return itemsBean1;
    }

    @Override
    public void deleteAd(AdBo adBo) {
        Ad ad = TransferUtils.Vo2Ad(adBo);
        ad.setDeleted(true);
        adMapper.updateByPrimaryKey(ad);
    }

    @Override
    public ItemsBean createAd(AdBo adBo) {
        //判断内容中有禁止的内容
        ItemsBean itemsBean1 = isIllegal(adBo);
        if (itemsBean1 != null) return itemsBean1;
        Ad ad = TransferUtils.Vo2Ad(adBo);
        ad.setDeleted(false);
        long l = System.currentTimeMillis();
        Date now = new Date(l);
        ad.setAddTime(now);
        ad.setUpdateTime(now);
        adMapper.insertSelective(ad);
        ItemsBean itemsBean = TransferUtils.Ad2Bo(ad);
        return itemsBean;
    }

    @Override
    public BaseRespData getCouponList(String name, Short type, Short status, BaseParamBo param) {
        CouponExample couponExample = new CouponExample();
        couponExample.setOrderByClause(param.getSort() + " " + param.getOrder());
        PageHelper.startPage(param.getPage(), param.getLimit());
        CouponExample.Criteria criteria = couponExample.createCriteria();
        if (name != null && !"".equals(name)) {
            criteria.andNameLike("%" + name + "%");
        }
        if (type != null && !"".equals(type)) {
            criteria.andTypeEqualTo(type);
        }
        if (status != null && !"".equals(status)) {
            criteria.andStatusEqualTo(status);
        }
        criteria.andDeletedEqualTo(false);

        List<CouponVo> couponList = new ArrayList<>();
        List<Coupon> coupons = couponMapper.selectByExample(couponExample);
        for (Coupon coupon : coupons) {
            CouponVo couponVo = TransferUtils.Coupon2CouponVo(coupon);
            couponList.add(couponVo);
        }
        PageInfo<Coupon> pageInfo = new PageInfo<>();
        int total = pageInfo.getPages();
        return BaseRespData.create(couponList, total);
    }

    @Override
    public CouponVo createCoupon(CouponBo couponVo) {
        if ((couponVo.getEndTime() == null || couponVo.getStartTime() == null) && ("".equals(couponVo.getDays()) || couponVo.getDays() == null)) {
            return null;
        }
        if(couponVo.getEndTime() == null || couponVo.getStartTime() == null){
            if(couponVo.getDays()<0){
                return null;
            }
        }
        Coupon coupon = TransferUtils.CouponBo2Coupon(couponVo, couponMapper);
        couponMapper.insertSelective(coupon);
        CouponVo couponBo = TransferUtils.Coupon2CouponVo(coupon);
        return couponBo;
    }

    @Override
    public CouponVo readCoupon(Integer id) {
        Coupon coupon = couponMapper.selectByPrimaryKey(id);
        CouponVo couponVo = TransferUtils.Coupon2CouponVo(coupon);
        return couponVo;
    }

    @Override
    public BaseRespData getCouponUser(Integer couponId, Integer userId, Short status, BaseParamBo param) {
        PageHelper.startPage(param.getPage(), param.getLimit());
        CouponUserExample couponUserExample = new CouponUserExample();
        couponUserExample.setOrderByClause(param.getSort() + " " + param.getOrder());
        CouponUserExample.Criteria criteria = couponUserExample.createCriteria();
        criteria.andCouponIdEqualTo(couponId);
        if (userId != null && !"".equals(userId)) {
            criteria.andUserIdEqualTo(userId);
        }
        if (status != null && !"".equals(status)) {
            criteria.andStatusEqualTo(status);
        }
        criteria.andDeletedEqualTo(false);
        List<CouponUserVo> couponUserVos = new ArrayList<>();
        List<CouponUser> couponUsers = couponUserMapper.selectByExample(couponUserExample);
        for (CouponUser couponUser : couponUsers) {
            CouponUserVo couponUserVo = TransferUtils.CouponUser2CouponUserVo(couponUser);
            couponUserVos.add(couponUserVo);
        }
        PageInfo<CouponUser> pageInfo = new PageInfo<>();
        int total = pageInfo.getPages();
        return BaseRespData.create(couponUserVos, total);
    }

    @Override
    public CouponVo updateCoupon(CouponBo couponBo) {
        Coupon cp = couponMapper.selectByPrimaryKey(couponBo.getId());
        //判断是否修改
        if (cp.getName().equals(couponBo.getName()) &&
                cp.getDesc().equals(couponBo.getDesc()) &&
                cp.getTag().equals(couponBo.getTag()) &&
                cp.getTotal().equals(couponBo.getTotal()) &&
                (cp.getDiscount().compareTo(couponBo.getDiscount())) == 0 &&
                (cp.getMin().compareTo(couponBo.getMin())) == 0 &&
                cp.getLimit().equals(couponBo.getLimit()) &&
                cp.getType().equals(couponBo.getType()) &&
                cp.getStatus().equals(couponBo.getStatus()) &&
                cp.getGoodsType().equals(couponBo.getGoodsType()) &&
                cp.getTimeType().equals(couponBo.getTimeType())) {
            if (cp.getDays() == null || "".equals(cp.getDays())) {
                if (cp.getStartTime().equals(couponBo.getStartTime()) &&
                        cp.getEndTime().equals(couponBo.getEndTime())) {
                    return null;
                }
            }
            if (cp.getStartTime() == null && cp.getEndTime() == null){
                if(cp.getDays().equals(couponBo.getDays())){
                    return null;
                }
            }
        }
        Coupon coupon = TransferUtils.CouponBo2Coupon(couponBo, couponMapper);
        coupon.setId(couponBo.getId());
        Date now = new Date(System.currentTimeMillis());
        coupon.setUpdateTime(now);
        if (coupon.getType() != 2) {
            coupon.setCode("");
        }
        couponMapper.updateByPrimaryKeySelective(coupon);
        CouponVo couponVo = TransferUtils.Coupon2CouponVo(coupon);
        return couponVo;
    }

    @Override
    public void deleteCoupon(CouponBo couponBo) {
        Coupon coupon = TransferUtils.CouponBo2Coupon(couponBo, couponMapper);
        coupon.setId(couponBo.getId());
        coupon.setDeleted(true);
        couponMapper.updateByPrimaryKey(coupon);
    }

    @Override
    public BaseRespData getTopicList(String title, String subtitle, BaseParamBo param) {
        PageHelper.startPage(param.getPage(), param.getLimit());
        TopicExample topicExample = new TopicExample();
        topicExample.setOrderByClause(param.getSort() + " " + param.getOrder());
        TopicExample.Criteria criteria = topicExample.createCriteria();
        if (title != null && !"".equals(title)) {
            criteria.andTitleLike("%" + title + "%");
        }
        if (subtitle != null && !"".equals(subtitle)) {
            criteria.andSubtitleLike("%" + subtitle + "%");
        }
        criteria.andDeletedEqualTo(false);
        List<Topic> topics = topicMapper.selectByExampleWithBLOBs(topicExample);
        ArrayList<TopicVo> topicVos = new ArrayList<>();
        for (Topic topic : topics) {
            TopicVo topicVo = TransferUtils.Topic2TopicVo(topic);
            topicVos.add(topicVo);
        }
        PageInfo<Topic> pageInfo = new PageInfo<>();
        int total = pageInfo.getSize();
        return BaseRespData.create(topicVos, total);
    }

    @Override
    public TopicVo createTopic(TopicBo topicBo) {
        Topic topic = TransferUtils.TopicBo2Topic(topicBo);
        Date now = new Date(System.currentTimeMillis());
        topic.setAddTime(now);
        topic.setUpdateTime(now);
        topic.setDeleted(false);
        topic.setSortOrder(1);
        topicMapper.insert(topic);
        TopicVo topicVo = TransferUtils.Topic2TopicVo(topic);
        return topicVo;
    }

    @Override
    public TopicVo updateTopic(TopicBo topicBo) {
        TopicExample topicExample = new TopicExample();
        TopicExample.Criteria criteria = topicExample.createCriteria();
        criteria.andIdEqualTo(topicBo.getId());
        List<Topic> topics = topicMapper.selectByExampleWithBLOBs(topicExample);
        Topic topic = topics.get(0);
        if (topic.getTitle().equals(topicBo.getTitle()) &&
                topic.getSubtitle().equals(topicBo.getSubtitle()) &&
                topic.getPrice().compareTo(topicBo.getPrice()) == 0 &&
                topic.getReadCount().equals(topicBo.getReadCount()) &&
                topic.getPicUrl().equals(topicBo.getPicUrl()) &&
                topic.getContent().equals(topicBo.getContent())) {
            return null;
        }
        Topic topicUse = TransferUtils.TopicBo2Topic(topicBo);
        Date now = new Date(System.currentTimeMillis());
        topicUse.setUpdateTime(now);
        topicUse.setAddTime(topic.getAddTime());
        topicUse.setSortOrder(topic.getSortOrder());
        topicUse.setDeleted(topic.getDeleted());
        topicMapper.updateByPrimaryKeyWithBLOBs(topicUse);
        TopicVo topicVo = TransferUtils.Topic2TopicVo(topicUse);
        return topicVo;
    }

    @Override
    public void deleteTopic(TopicBo topicBo) {
        Topic topic = TransferUtils.TopicBo2Topic(topicBo);
        topic.setDeleted(true);
        topic.setAddTime(topicBo.getAddTime());
        topic.setUpdateTime(topicBo.getUpdateTime());
        topic.setSortOrder(topicBo.getSortOrder());
        topicMapper.updateByPrimaryKeyWithBLOBs(topic);
    }

    @Override
    public BaseRespData getGrouponRulesList(Integer goodsId, BaseParamBo param) {
        PageHelper.startPage(param.getPage(), param.getLimit());
        GrouponRulesExample grouponRulesExample = new GrouponRulesExample();
        grouponRulesExample.setOrderByClause(param.getSort() + " " + param.getOrder());
        GrouponRulesExample.Criteria criteria = grouponRulesExample.createCriteria();
        if (goodsId != null && !"".equals(goodsId)) {
            criteria.andGoodsIdEqualTo(goodsId);
        }
        criteria.andDeletedEqualTo(false);
        List<GrouponRules> grouponRules = grouponRulesMapper.selectByExample(grouponRulesExample);
        List<GrouponRulesVo> grouponRulesVos = new ArrayList<>();
        for (GrouponRules grouponRule : grouponRules) {
            GrouponRulesVo grouponRulesVo = TransferUtils.GrouponRules2GrouponRulesVo(grouponRule);
            grouponRulesVos.add(grouponRulesVo);
        }
        PageInfo<GrouponRules> pageInfo = new PageInfo<>();
        int total = pageInfo.getSize();
        return BaseRespData.create(grouponRulesVos, total);
    }

    @Override
    public Integer updateGrouponRules(GrouponRulesBo grouponRulesBo) {
        //判断是否修改
        GrouponRules grouponRule = grouponRulesMapper.selectByPrimaryKey(grouponRulesBo.getId());
        if (grouponRule.getGoodsId().equals(grouponRulesBo.getGoodsId()) &&
                grouponRule.getDiscount().compareTo(grouponRulesBo.getDiscount()) == 0 &&
                grouponRule.getDiscountMember().equals(grouponRulesBo.getDiscountMember()) &&
                grouponRule.getExpireTime().equals(grouponRulesBo.getExpireTime())) {
            return 0;
        }
        //判断商品id是否存在
        if (existGoodsId(grouponRulesBo.getGoodsId())) {
            GrouponRules grouponRules = TransferUtils.GrouponRulesBo2GrouponRules(grouponRulesBo);
            Date now = new Date(System.currentTimeMillis());
            grouponRules.setUpdateTime(now);
            grouponRulesMapper.updateByPrimaryKeySelective(grouponRules);
            return 2;
        }
        return 1;
    }

    @Override
    public GrouponRulesVo createGrouponRules(GrouponRulesCreateBo grouponRulesCreateBo) {
        //判断商品id是否存在
        if (!existGoodsId(grouponRulesCreateBo.getGoodsId())) {
            return null;
        }
        Goods goods = goodsMapper.selectByPrimaryKey(grouponRulesCreateBo.getGoodsId());
        GrouponRules grouponRules = new GrouponRules();
        grouponRules.setGoodsId(grouponRulesCreateBo.getGoodsId());
        grouponRules.setGoodsName(goods.getName());
        grouponRules.setPicUrl(goods.getPicUrl());
        grouponRules.setDiscount(grouponRulesCreateBo.getDiscount());
        grouponRules.setDiscountMember(grouponRulesCreateBo.getDiscountMember());
        Date now = new Date(System.currentTimeMillis());
        grouponRules.setAddTime(now);
        grouponRules.setUpdateTime(now);
        grouponRules.setExpireTime(grouponRulesCreateBo.getExpireTime());
        grouponRules.setDeleted(false);
        grouponRulesMapper.insert(grouponRules);
        GrouponRulesVo grouponRulesVo = TransferUtils.GrouponRules2GrouponRulesVo(grouponRules);
        return grouponRulesVo;
    }

    @Override
    public void deleteGrouponRules(GrouponRulesBo grouponRulesBo) {
        GrouponRules grouponRules = TransferUtils.GrouponRulesBo2GrouponRules(grouponRulesBo);
        grouponRules.setDeleted(true);
        grouponRulesMapper.updateByPrimaryKeySelective(grouponRules);
    }

    @Override
    public BaseRespData getListRecord(Integer goodsId, BaseParamBo param) {
        PageHelper.startPage(param.getPage(), param.getLimit());
        List<Groupon> groupons = null;
        if (goodsId != null && !"".equals(goodsId)) {
            groupons = grouponMapper.selectWithMultilist(goodsId);
        } else {
            GrouponExample grouponExample = new GrouponExample();
            grouponExample.setOrderByClause(param.getSort() + " " + param.getOrder());
            GrouponExample.Criteria criteria = grouponExample.createCriteria();
            criteria.andDeletedEqualTo(false);
            groupons = grouponMapper.selectByExample(grouponExample);
        }
        List<ListRecordVo> items = new ArrayList<>();
        for (Groupon groupon : groupons) {
            ListRecordVo listRecordVo = new ListRecordVo();
            GrouponVo grouponVo = TransferUtils.Groupon2GrouponVo(groupon);
            GrouponRules grouponRules = grouponRulesMapper.selectByPrimaryKey(groupon.getRulesId());
            GrouponRulesVo grouponRulesVo = TransferUtils.GrouponRules2GrouponRulesVo(grouponRules);
            Goods goods = goodsMapper.selectByPrimaryKey(grouponRules.getGoodsId());
            GoodsVo goodsVo = TransferUtils.Goods2GoodsVo(goods);
            listRecordVo.setGroupon(grouponVo);
            listRecordVo.setGoods(goodsVo);
            listRecordVo.setRules(grouponRulesVo);
            items.add(listRecordVo);
        }
        PageInfo<Groupon> pageInfo = new PageInfo<>();
        int total = pageInfo.getSize();
        return BaseRespData.create(items, total);
    }

    //违规信息判断
    private ItemsBean isIllegal(AdBo adBo) {
        List<String> words = prohibition.getWords();
        for (String word : words) {
            if (adBo.getContent().contains(word)) {
                ItemsBean itemsBean = new ItemsBean();
                itemsBean.setContent("违规");
                return itemsBean;
            }
        }
        return null;
    }

    //判断商品id是否存在
    private boolean existGoodsId(Integer goodsId) {
        GoodsExample goodsExample = new GoodsExample();
        GoodsExample.Criteria criteria = goodsExample.createCriteria();
        criteria.andDeletedEqualTo(false);
        List<Goods> goods = goodsMapper.selectByExampleWithBLOBs(goodsExample);
        for (Goods good : goods) {
            if (good.getId().equals(goodsId)) {
                return true;
            }
        }
        return false;
    }
}
